<?php
declare (strict_types = 1);

namespace app\admin\controller\admin;

use app\admin\model\admin\AdminRole;
use app\admin\model\admin\AdminUser as AdminModel;
use app\admin\model\admin\AdminUserRole;
use app\admin\model\admin\Role;
use app\admin\validate\admin\Admin as AdminValidate;
use app\admin\validate\admin\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;


class Admin extends Base
{
    protected $configParam = ['advisory_pool_search_time', 'warning_price', 'order_buffer'];

    public function index()
    {

        if (Request::isAjax()) {
            $where = [];
            //按用户名查找
            if ($search = input('get.username')) {
                $where[] = ['username', 'like', "%" . $search . "%"];
            }
           
            $list = AdminModel::order('id','desc')
                ->where('id','>','1')
                ->withoutField('password,rand_key,delete_time')
                ->where($where)
                ->paginate(Request::get('limit'));

            foreach ($list as $k => $v){
                $list[$k]['campus_name'] = 'xxx';
            }
            $this->jsonApi('', 0, $list->items(), ['count' => $list->total(), 'limit' => Request::get('limit')]);
        }
        return View::fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (Request::isAjax()) {
            $data = Request::post();
            //验证
            $validate = new AdminValidate;
            if(!$validate->scene('add')->check($data))
                $this->jsonApi($validate->getError(),201);
            Db::startTrans();
            try {
                //substr(md5(trim($password)),8,16),
                $password =  md5(trim($data['password']));
                $adminUser = AdminModel::create(array_merge($data, [
                    'password' => substr($password,8,16)
                ]));
                $temp = [];
                foreach ($data['roles'] as $v){
                    $temp[] = [
                        'admin_id' => $adminUser->id,
                        'role_id' => $v,
                    ];
                }
                $relationModel = new AdminUserRole();
                $relationModel->saveAll($temp);

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->jsonApi('添加失败',201, $e->getMessage());
            }
            $this->jsonApi('添加成功');
        }
        return View::fetch('form',[ 'roles' => AdminRole::select()]);
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        $formData = AdminModel::with('roles')->where('id',$id)->find();

        if (Request::isAjax()) {
            //获取数据
            $data = Request::post();
            //判断是否存在状态这个字段
            if (key_exists('status',$data)) {
                $msg = $data['status'] == 1 ? '启用' : '禁用';
                $result = AdminModel::update($data,[],['id','status']);
                //判断结果
                if ($result) return $this->jsonApi($msg . '成功');
                return $this->jsonApi($msg . '失败',400);
            } else {
                $data['id'] = $formData['id'];
                //验证
                $validate = new AdminValidate;
                if(!$validate->scene('edit')->check($data))
                    $this->jsonApi($validate->getError(),201);
                $formData->username = $data['username'];
                $formData->nickname = $data['nickname'];
                Db::startTrans();
                try {
                    //清除原先的角色
                    AdminUserRole::where('admin_id',$id)->delete();
                    //添加新的角色
                    $temp = [];
                    foreach ($data['roles'] as $v){
                        $temp[] = [
                            'admin_id' => $id,
                            'role_id' => $v,
                        ];
                    }
                    (new AdminUserRole())->saveAll($temp);
                    $formData->save();
                    $this->rm();
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    $this->jsonApi('更新失败',201, $e->getMessage());
                }
                $this->jsonApi('更新成功');
            }
        }else{
            $roles = AdminRole::select();
            foreach ($roles as $k=>$role){
                if (isset($formData->roles) && !$formData->roles->isEmpty()){
                    foreach ($formData->roles as $v){
                        if ($role['id'] == $v['id']){
                            $roles[$k]['own'] = true;
                        }
                    }
                }
            }
        }
        return View::fetch('form',[
            'formData' => $formData, 'roles' =>$roles
        ]);
    }

    /**
     * 删除
     */
    public function del($id)
    {
        $admin = AdminModel::find($id);
        if($admin){
            try{
                //删除中间表
                AdminUserRole::where('admin_id', $admin['id'])->delete();
                $admin->delete();
                $this->rm();
            }catch (\Exception $e){
                $this->jsonApi('删除失败',201, $e->getMessage());
            }
            $this->jsonApi('删除成功');
        }
    }

    /**
     * 选中删除
     */
    public function del_all()
    {
        $ids = Request::param('ids');
        if (!is_array($ids)){
            $this->jsonApi('参数错误',201);
        }
        try{
            AdminModel::destroy($ids);
            //删除中间表
            AdminUserRole::whereIn('admin_id', $ids)->delete();
            $this->rm();
        }catch (\Exception $e){
            $this->jsonApi('删除失败',201, $e->getMessage());
        }
        $this->jsonApi('删除成功');
    }

    public function systemIndex()
    {
        if (Request::isAjax()){
            $postData = Request::param();
            $validate = new Config();
            if(!$validate->check($postData))
                $this->error($validate->getError());
            Db::startTrans();
            try {
                foreach ($postData as $k => $v){
                    Db::table('admin_config')->where('name', $k)->update(['value' => $v]);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('设置失败');
            }
            $this->success('设置成功');
        }
        $data = Db::table('admin_config')->where('name', 'in', $this->configParam)->column('value', 'name');
        return View::fetch('',[
            'data' => $data
        ]);
    }
}
